<template>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large"
             @keyup.enter="login">
        <el-form-item prop="email">
            <el-input v-model="form.email" prefix-icon="Message" clearable
                      :placeholder="$t('login.userPlaceholder')"></el-input>
        </el-form-item>
        <el-form-item prop="captcha" style="margin-bottom: 35px;">
            <div class="login-msg-yzm">
                <el-input v-model="form.captcha" prefix-icon="Unlock" clearable
                          :placeholder="$t('login.emailPlaceholder')"></el-input>
                <el-button @click="getCaptcha(loginForm)" :disabled="disabled">
                    {{ $t('login.emailGet') }}
                    <span v-if="disabled">({{ countdown }})</span>
                </el-button>
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" style="width: 100%;" :loading="islogin" round @click="login">
                {{ $t('login.signIn') }}
            </el-button>
        </el-form-item>
        <div class="login-reg">
            {{ $t('login.noAccount') }}
            <router-link to="/register">{{ $t('login.createAccount') }}</router-link>
        </div>
    </el-form>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, FormRules} from 'element-plus'
import {useI18n} from "vue-i18n";
import {sendEmailCaptcha} from "@/api/modules/guest.ts";
import {AuthRequestModel} from "@/models/authModel.ts";
import {getPolicyApi, loginApi, logoutApi} from "@/api/modules/auth.ts";
import router from "@/router";
import {useAuthStore} from "@/store/modules/auth.ts";
import {useMenuStore} from "@/store/modules/menu.ts";

const {t} = useI18n();
const authStore = useAuthStore();
const menuStore = useMenuStore();

const form = reactive<AuthRequestModel>({
    type: 'captcha',
    email: '',
    captcha: '',
});

const rules = reactive<FormRules<AuthRequestModel>>({
    email: [
        {required: true, message: t('login.emailError')}
    ],
    captcha: [
        {required: true, message: t('login.emailErrorCode')}
    ]
})

const disabled = ref(false);
const countdown = ref(0);
const islogin = ref(false);
const loginForm = ref<FormInstance>();

const getCaptcha = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validateField("email", async (valid) => {
        if (!valid) return;
        try {
            await sendEmailCaptcha({email: form.email});
            disabled.value = true;
            countdown.value = 60;
            const t = setInterval(() => {
                countdown.value -= 1;
                if (countdown.value < 1) {
                    clearInterval(t)
                    disabled.value = false;
                    countdown.value = 0;
                }
            }, 1000);
        } catch (error) {
            ElMessage.error("发送验证码失败，请重试！");
        }
    });
};

const login = async () => {
    const formInstance = loginForm.value;
    if (!formInstance) return;
    try {
        await formInstance.validate();
        islogin.value = true;
        const loginData = await loginApi(form);
        authStore.token = loginData.data.token;
        authStore.userInfo = loginData.data.user;

        let policyData = await getPolicyApi();
        if (policyData.data.menus.length === 0) {
            ElMessageBox.confirm('当前账户无任何菜单权限，请联系系统管理员!', '提示', {
                type: 'warning',
                confirmButtonClass: 'el-button--primary',
                showCancelButton: false,
            }).then(async () => {
                await logoutApi();
                authStore.$reset();
            });
            return;
        }
        menuStore.list = policyData.data.menus;
        menuStore.permissions = policyData.data.permissions;
        await router.replace({path: '/'});
        ElMessage.success("欢迎回来!");
    } catch (error) {
        console.log(error);
    } finally {
        islogin.value = false;
    }
}
</script>

<style></style>
